document.addEventListener('DOMContentLoaded', () => {
  // DOM elements
  const browserEl = document.getElementById('browser');
  const playerContainerEl = document.getElementById('player-container');
  const videoPlayerEl = document.getElementById('video-player');
  const videoTitleEl = document.getElementById('video-title');
  const breadcrumbEl = document.getElementById('breadcrumb');
  const backButtonEl = document.getElementById('back-button');
  
  // State
  let currentPath = '';
  let currentVideo = null;
  
  // Initialize
  loadDirectory(currentPath);
  
  // Event listeners
  backButtonEl.addEventListener('click', () => {
    hidePlayer();
    showBrowser();
  });
  
  // Functions
  async function loadDirectory(path) {
    showLoading();
    try {
      const response = await fetch(`/api/videos?path=${encodeURIComponent(path)}`);
      if (!response.ok) throw new Error('Failed to load directory');
      
      const items = await response.json();
      renderBrowser(items);
      renderBreadcrumb(path);
    } catch (error) {
      console.error('Error loading directory:', error);
      showError('Failed to load directory. Please try again.');
    }
  }
  
  function renderBrowser(items) {
    browserEl.innerHTML = '';
    
    if (items.length === 0) {
      browserEl.innerHTML = '<div class="loading">No items found in this directory</div>';
      return;
    }
    
    // Sort: folders first, then files
    items.sort((a, b) => {
      if (a.isDirectory && !b.isDirectory) return -1;
      if (!a.isDirectory && b.isDirectory) return 1;
      return a.name.localeCompare(b.name);
    });
    
    items.forEach(item => {
      if (item.isDirectory || item.isVideo) {
        const itemEl = document.createElement('div');
        itemEl.className = `item ${item.isDirectory ? 'item-folder' : 'item-video'}`;
        
        itemEl.innerHTML = `
          <div class="item-thumbnail">
            <div class="${item.isDirectory ? 'folder-icon' : 'video-icon'}">
              ${item.isDirectory ? '📁' : '🎬'}
            </div>
          </div>
          <div class="item-info">
            <div class="item-name">${item.name}</div>
          </div>
        `;
        
        itemEl.addEventListener('click', () => {
          if (item.isDirectory) {
            currentPath = item.path;
            loadDirectory(currentPath);
          } else if (item.isVideo) {
            playVideo(item);
          }
        });
        
        browserEl.appendChild(itemEl);
      }
    });
  }
  
  function renderBreadcrumb(path) {
    breadcrumbEl.innerHTML = '';
    
    // Home link
    const homeLink = document.createElement('a');
    homeLink.textContent = 'Home';
    homeLink.addEventListener('click', () => {
      currentPath = '';
      loadDirectory('');
    });
    breadcrumbEl.appendChild(homeLink);
    
    if (path) {
      breadcrumbEl.appendChild(document.createTextNode(' / '));
      
      const parts = path.split('/');
      let currentPart = '';
      
      parts.forEach((part, index) => {
        currentPart += part;
        
        const partLink = document.createElement('a');
        partLink.textContent = part;
        
        if (index < parts.length - 1) {
          partLink.addEventListener('click', () => {
            currentPath = currentPart;
            loadDirectory(currentPath);
          });
          breadcrumbEl.appendChild(partLink);
          breadcrumbEl.appendChild(document.createTextNode(' / '));
          currentPart += '/';
        } else {
          breadcrumbEl.appendChild(document.createTextNode(part));
        }
      });
    }
  }
  
  function playVideo(video) {
    currentVideo = video;
    videoTitleEl.textContent = video.name;
    videoPlayerEl.src = `/videos/${encodeURIComponent(video.path)}`;
    videoPlayerEl.load();
    
    hideBrowser();
    showPlayer();
  }
  
  function showLoading() {
    browserEl.innerHTML = '<div class="loading">Loading...</div>';
  }
  
  function showError(message) {
    browserEl.innerHTML = `<div class="loading">${message}</div>`;
  }
  
  function showBrowser() {
    browserEl.style.display = 'grid';
  }
  
  function hideBrowser() {
    browserEl.style.display = 'none';
  }
  
  function showPlayer() {
    playerContainerEl.style.display = 'flex';
  }
  
  function hidePlayer() {
    playerContainerEl.style.display = 'none';
    videoPlayerEl.pause();
    videoPlayerEl.src = '';
  }
}); 